//app.js
var api;
const util = require('utils/util.js');
App({
  api: require('api.js'),
  setApi: function() {
    function getNewApiUri(api) {
      for (var i in api) {
        if (typeof api[i] != 'string') {
          api[i] = getNewApiUri(api[i]);
        }
      }
      return api;
    }

    this.api = getNewApiUri(this.api);
  },
  onLaunch: function() {
    var that = this;
    that.setApi();
    api = that.api;

    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager();
      updateManager.onUpdateReady(function() {
        wx.showModal({
          title: '更新提示',
          showCancel: false,
          content: '有新版本啦！点击更新即可升级 :)',
          confirmText: '更新',
          complete: function() {
            // applyUpdate 应用新版本并重启
            updateManager.applyUpdate();
          }
        });
      });
    }
    this.checkIsIPhoneX();

    var expiration = util.formatDate(Date.now());
    wx.setStorageSync('index_data_expiration', expiration);

    wx.request({
      url: 'https://tianqiapi.com/ip/',
      data: {},
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        // 游客访问
        that.sendRequest({
          url: api.public.visit,
          method: 'post',
          data: {
            user_id: 0,
            fecility: 2,
            ip: res.data.ip
          },
          success: function(res) {}
        });
      }
    });

    this.onlineTimer();

    // wx.cloud.init();
  },
  onShow() {
    var logging = wx.getStorageSync('_logining');
    if (logging) {
      this.checkUnReadMsg();
    }
  },
  saveFormId(formId) {
    // wx.cloud.callFunction({
    //   name: 'form_id_collect',
    //   data: {
    //     form_id: formId
    //   }
    // });
    console.log('formId:' + formId);
    var logging = wx.getStorageSync('_logining');
    if (logging) {
      if (formId != 'the formId is a mock one') {
        this.sendRequest({
          hideLoading: true,
          url: api.public.add_formid,
          method: 'post',
          data: {
            formid: formId
          },
          success: function(res) {}
        });
      }
    }
  },
  onlineTimer() {
    let self = this;
    // 在线时长触发，每10分钟
    setInterval(() => {
      var logging = wx.getStorageSync('_logining');
      if (logging) {
        self.sendRequest({
          hideLoading: true,
          url: api.public.online_time,
          method: 'post',
          data: {
            fecility: 2,
            time: 10
          },
          success: function(res) {}
        });
      }
    }, 1000 * 60 * 10);
  },
  checkIsIPhoneX: function() {
    const self = this;
    wx.getSystemInfo({
      success: function(res) {
        var model = res.model.toLowerCase();
        // 根据 model 进行判断
        if (
          model.search('iphone x') != -1 ||
          model.search('iphone xr') != -1 ||
          model.search('iphone xs') != -1
        ) {
          self.globalData.isIPX = true;
        }
        // 判断IOS
        if (model.search('iphone') != -1) {
          self.globalData.isIOS = true;
        }
      }
    });
  },
  // 检查是否有新消息
  checkUnReadMsg() {
    this.sendRequest({
      url: api.pm.type,
      success: function(res) {
        let types = res.data || [];
        if (types.length > 0) {
          types.map(type => {
            if (type.if_read == 1) {
              wx.showTabBarRedDot({ index: 2 });
              // wx.setTabBarBadge({ index: 2, text: '41' });
              return;
            }
          });
        }
      }
    });
  },
  //回到顶部
  goTop: function(e) {
    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: 0
      });
    } else {
      wx.showModal({
        title: '提示',
        content:
          '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      });
    }
  },
  checkSession: function(callback, url) {
    let that = this;
    wx.checkSession({
      success: function() {
        that.checkToken();
        typeof callback == 'function' && callback();
      },
      fail: function() {
        that._logining = false;
        wx.setStorageSync('_logining', false);
      }
    });
  },
  _sendCode: function(code, url) {
    let that = this;
    var access_info = wx.getStorageSync('access_info');
    var access_detail = access_info.detail;
    wx.request({
      url: api.passport.login,
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        code: code,
        encrypted_data: access_detail.encryptedData,
        iv: access_detail.iv
      },
      success: function(res) {
        if (res.data.status == 200) {
          that._logining = true;
          wx.setStorageSync('_logining', true);
          let current_user_id = res.data.data.user_list[0].user_id;
          let access_token = res.data.data.user_list[0].school_token;
          wx.setStorageSync('current_user_id', current_user_id);
          wx.setStorageSync('access_token', access_token);
          wx.setStorageSync('openid', res.data.data.openid);
          //判断是否完善过信息
          that.sendRequest({
            url: api.public.student_info,
            success: function(res) {
              wx.setStorageSync('old_student_info', res.data);
              if (res.data.grade_id != undefined && res.data.grade_id > 0) {
                that.forwardPage(url);
              } else {
                that.globalData.old_student_info = res.data;
                wx.redirectTo({
                  url:
                    '/pages/base_info/base_info?url=' + decodeURIComponent(url)
                });
              }
            }
          });

          wx.request({
            url: 'https://tianqiapi.com/ip/',
            data: {},
            method: 'POST',
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            success: function(res) {
              // 访问触发
              that.sendRequest({
                url: api.public.visit,
                method: 'post',
                data: {
                  user_id: current_user_id,
                  fecility: 2,
                  ip: res.data.ip
                },
                success: function(res) {}
              });
            }
          });
          that.checkUnReadMsg();
        }
      },
      fail: function(res) {
        that._logining = false;
        wx.setStorageSync('_logining', false);
        console.log('_sendCode fail');
      }
    });
  },
  forwardPage(url) {
    if (url != undefined) {
      if (
        url.indexOf('my/my') > -1 ||
        url.indexOf('study/study') > -1 ||
        url.indexOf('index/index') > -1 ||
        url.indexOf('coach_center/coach_center') > -1
      ) {
        if (url.indexOf('my/my') > -1) {
          wx.switchTab({
            url: url
          });
        } else {
          wx.switchTab({
            url: '/pages/index/index'
          });
        }
      } else {
        wx.redirectTo({
          url: decodeURIComponent(url)
        });
      }
    } else {
      wx.switchTab({
        url: '/pages/index/index'
      });
    }
  },
  //判断是否有登陆token
  checkToken: function() {
    var that = this;
    let token = wx.getStorageSync('access_token') || '';
    if (token == undefined || token == '') {
      that._logining = false;
      that.globalData._logging = false;
      wx.setStorageSync('_logining', false);
    } else {
      that._logining = true;
      wx.setStorageSync('_logining', true);
    }
  },
  //跳转登录页
  toAuth: function(url, is_storage_url) {
    if (url == undefined) {
      url = '/pages/index/index';
    }
    if (is_storage_url == 1) {
      wx.redirectTo({
        url: '/pages/auth/auth?is_storage_url=' + is_storage_url
      });
    } else {
      wx.redirectTo({
        url: '/pages/auth/auth?url=' + url
      });
    }
  },
  globalData: {
    isIPX: false,
    userInfo: null
  },
  sendRequest: function(param) {
    let that = this;
    let data = param.data || {};
    let header = param.header;
    let requestUrl;
    let token = wx.getStorageSync('access_token') || '';

    requestUrl = param.url;

    if (!param.hideLoading) {
      this.showLoading({
        title: '加载中...'
      });
    }

    wx.request({
      url: requestUrl,
      data: data,
      method: param.method || 'GET',
      header: header || {
        token: token,
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        if (res.statusCode && res.statusCode != 200) {
          if (res.statusCode == 403) {
            that.toAuth();
            return;
          }
          that.hideToast();
          that.showToast({
            title: '请求异常',
            icon: 'none'
          });
          return;
        }
        typeof param.success == 'function' && param.success(res.data);
      },
      fail: function(res) {
        console.log('request fail:', requestUrl, res.errMsg);
        that.hideToast();
        if (res.errMsg == 'request:fail url not in domain list') {
          that.showToast({
            title: '请配置正确的请求域名',
            icon: 'none',
            duration: 2000
          });
        }
        typeof param.fail == 'function' && param.fail(res.data);
      },
      complete: function(res) {
        param.hideLoading || that.hideLoading();
        typeof param.complete == 'function' && param.complete(res.data);
      }
    });
  },
  _logining: false,
  _login: function(url) {
    let that = this;

    wx.login({
      success: function(res) {
        if (res.code) {
          that._sendCode(res.code, url);
        } else {
          console.log('获取用户登录态失败！' + res.errMsg);
        }
      },
      fail: function(res) {
        that._logining = false;
        wx.setStorageSync('_logining', false);
        console.log('login fail: ' + res.errMsg);
      }
    });
  },
  setPageTitle: function(title) {
    wx.setNavigationBarTitle({
      title: title
    });
  },
  showToast: function(param) {
    wx.showToast({
      title: param.title,
      icon: param.icon,
      duration: param.duration || 1500,
      success: function(res) {
        typeof param.success == 'function' && param.success(res);
      },
      fail: function(res) {
        typeof param.fail == 'function' && param.fail(res);
      },
      complete: function(res) {
        typeof param.complete == 'function' && param.complete(res);
      }
    });
  },
  hideToast: function() {
    wx.hideToast();
  },
  showLoading: function(param) {
    wx.showLoading({
      title: param.title,
      success: function(res) {
        typeof param.success == 'function' && param.success(res);
      },
      fail: function(res) {
        typeof param.fail == 'function' && param.fail(res);
      },
      complete: function(res) {
        typeof param.complete == 'function' && param.complete(res);
      }
    });
  },
  hideLoading: function() {
    wx.hideLoading();
  }
});
